<?php
namespace App\Logic\Shipping;

use App\Models\Shipping\SSku;
use App\Models\Shipping\SSkuApply;
use Illuminate\Support\Facades\DB;
class InitSSkuStatus
{
    /**
     * 设定：每月15日与月末
     */
    public static function exe(){
        $t = date('t');
        $day = date('j');//当前月中的第几天
        if($day == 15 || $day == $t){
            try{
                $shippingDate = SSkuApply::initShippingDate();
                $sDate = array_key_first($shippingDate);
                $eDate = array_key_last($shippingDate);
                SSku::query()->orderBy('id')
                    ->chunk(500, function ($ss) use ($sDate,$eDate){
                        DB::beginTransaction();
                        foreach ($ss as $_ss){
                            if($_ss->status != 2)continue;
                            $_ss->status = 1;
                            $_ss->save();
                            $sca = SSkuApply::query()
                                ->where('area_id',$_ss->area_id)
                                ->where('psku_id',$_ss->psku_id)
                                ->where('shipping_date','>=',$sDate)
                                ->where('shipping_date','<=',$eDate)
                                ->get();
                            foreach($sca as $_sca){
                                $_sca->apply_num = $_sca->last_apply_num;
                                $_sca->save();
                            }
                        }
                        DB::commit();
                    });
            }catch (\Exception $e){
                DB::rollBack();
                report($e);
            }
        }else{
            die('不符合更新条件');
        }
    }
}
